package com.lagou.controller;

import com.lagou.pojo.AuthCode;
import com.lagou.service.AuthCodeService;
import com.lagou.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/api/code")
@RefreshScope
public class CodeController {

    @Reference
    private AuthCodeService authCodeService;

    @Reference
    private EmailService emailService;

    @Value("${test.code}")
    private String defaultCode;

    @RequestMapping("/create/{email}")
    public boolean create(@PathVariable("email") String email){
        AuthCode authCode = authCodeService.create(email);
        if(authCode == null) return false;
        return true;
    }

    @RequestMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable("email") String email, @PathVariable("code") String code){
        AuthCode lastAuthCode = authCodeService.findLastAuthCode(email);
        if(new Date().after(lastAuthCode.getExpiretime())){
            return 2;
        }
        if(code.equals(lastAuthCode.getCode())){
            return 0;
        }
        return 1;
    }

    @RequestMapping("/email/test")
    public String test(){
        return defaultCode;
    }
}
